package org.codeart.api_driver.controller;

import org.codeart.api_driver.service.OrderApiService;
import org.codeart.common.constant.IdentityEnum;
import org.codeart.common.dto.OrderInfo;
import org.codeart.common.dto.TokenResult;
import org.codeart.common.request.OrderRequest;
import org.codeart.common.util.JwtUtils;
import org.codeart.common.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderApiService orderService;

    @PostMapping("/to-pick-up-passenger")
    public R<Void> toPickUpPassenger(@RequestBody OrderRequest orderRequest) {
        boolean b = orderService.toPickUpPassenger(orderRequest);
        if (b) {
            return R.ok();
        }
        return R.fail("更新订单失败");
    }

    /**
     * 到达乘客上车点
     */
    @PostMapping("/arrived-departure")
    public R<Void> arriveDeparture(@RequestBody OrderRequest orderRequest) {
        boolean b = orderService.arriveDeparture(orderRequest);
        if (b) {
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 司机接到乘客
     */
    @PostMapping("/pick-up-passenger")
    public R<Void> pickUpPassenger(@RequestBody OrderRequest orderRequest) {
        boolean b = orderService.pickUpPassenger(orderRequest);
        if (b) {
            return R.ok();
        }
        return R.fail("订单异常");
    }

    /**
     * 乘客到达目的地，行程终止
     */
    @PostMapping("/passenger-get-off")
    public R<Void> passengerGetOff(@RequestBody OrderRequest orderRequest) {
        boolean b = orderService.passengerGetOff(orderRequest);
        if (b) {
            return R.ok();
        }
        return R.fail("订单异常");
    }

    @PostMapping("/cancel")
    public R<Void> cancel(@RequestParam("orderId") Long orderId) {
        boolean b = orderService.cancel(orderId);
        if (b) {
            return R.ok();
        }
        return R.fail("订单取消失败");
    }

    @GetMapping("/detail")
    public R<OrderInfo> detail(Long orderId) {
        return orderService.detail(orderId);
    }

    @GetMapping("/current")
    public R<OrderInfo> currentOrder(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader("Authorization");
        TokenResult tokenResult = JwtUtils.parseToken(authorization);
        String identity = tokenResult.getIdentity();
        if (!identity.equals(IdentityEnum.DRIVER.value())) {
            return R.fail("当前操作无权限, 仅限司机操作");
        }
        String phone = tokenResult.getPhone();
        return orderService.currentOrder(phone, IdentityEnum.DRIVER.value());
    }

}
